package com.frxuexi.mynews.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.frxuexi.mynews.entity.NewsEntity
import com.frxuexi.mynews.intent.LoginIntent
import com.frxuexi.mynews.intent.NewsIntent
import com.frxuexi.mynews.repository.LoginRepository
import com.frxuexi.mynews.repository.NewsTypeRepository
import com.frxuexi.mynews.state.LoginState
import com.frxuexi.mynews.state.NewsState
import com.google.gson.Gson
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.RequestBody

class LoginViewModel:ViewModel() {
    val resp by lazy { LoginRepository() }

    val channel= Channel<LoginIntent>(Channel.UNLIMITED)

    private var _state= MutableStateFlow<LoginState>(LoginState.Loading)
    val loginState: StateFlow<LoginState>
        get() = _state

    init {
        handlerIntent()
    }

    private fun handlerIntent() {
        viewModelScope.launch {
            channel.consumeAsFlow().collect{
                when(it){
                    is LoginIntent.login->
                        login(it.name,it.pass)
                }
            }
        }
    }

    fun login(name:String,pass:String){
        val map = hashMapOf<String, Any>(Pair("name", name), Pair("password", pass))
        val json = Gson().toJson(map)
        val body = RequestBody.create(MediaType.parse("application/json"), json)
        viewModelScope.launch {
            resp.login(body).collect{
                if(it.code==0){
                    _state.value= LoginState.onSucess(it.data)
                }else{
                    _state.value= LoginState.onError(it.msg)
                }
            }
        }
    }
}